package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.material.dao.WlbmJldwDao;
import com.liangtian.mdm.material.model.*;
import com.liangtian.mdm.material.service.*;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.util.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

@Controller
@RequestMapping("/wlLbmbController")
public class WlLbmbController extends BaseController {

    @Autowired
    private WlLbmbService wlLbmbService;

    @Autowired
    private WlLbmbtzlService wlLbmbtzlService;

    // 日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @Autowired
    JdbcDao jdbcDao;

    private ExcelImport excelImport = new ExcelImport();

    @Autowired
    private WlLbService wlLbService;

    @Autowired
    private WlFhService wlFhService;

    @Autowired
    private WlbmJldwService wlbmJldwService;

    @Autowired
    private WlbmJldwDao wlbmJldwDao;

    @Autowired
    private WlLbmbtzlqzService wlLbmbtzlqzService;

    private List<WlLbmb> wlLbMbListByExport = null;
    private Map<String, Object> wlmbmap = null;

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbListByCond", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlLbmbListByCond(HttpServletRequest request, WlLbmb lbmb) {
        Map paramMap = RequestUtils.paramToMap(request, WlLbmb.class, false);
        PageInfo pageInfo = wlLbmbService.getWlLbmbListByCond(paramMap);
        List l = pageInfo.getList();
        wlLbMbListByExport = pageInfo.getList();
        wlmbmap = paramMap;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbById", method = RequestMethod.POST)
    public String getWlLbmbById(WlLbmb wlmb) {
        WlLbmb lbmb = null;
        try {
            lbmb = wlLbmbService.getWlLbmbById(wlmb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(lbmb);
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbListByCondByAdd", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlLbmbListByCondByAdd(HttpServletRequest request, WlLbmb lbmb) {
		/*if("".equals(lbmb.getLbbm()) || lbmb.getLbbm() == null){
			return null;
		}*/
        Map paramMap = RequestUtils.paramToMap(request, WlLbmb.class, false);
        String states = (String) paramMap.get("state");
        if (!StringUtils.isEmpty(states) && states.indexOf(",") != -1) {
            paramMap.put("states", paramMap.get("state"));
            paramMap.put("state", "");
        }
        PageInfo pageInfo = wlLbmbService.getWlLbmbListByCondByAdd(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbListCountByCond", method = RequestMethod.POST)
    public JSONObject getWlLbmbListCountByCond(HttpServletRequest request, WlLbmb lbmb) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = wlLbmbService.getWlLbmbListCountByCond(lbmb);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @RequestMapping(value = "/insertWlLbmb", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertWlLbmb(WlLbmb lbmb, HttpServletRequest request) {
        // 获取当前日期
        Date date = new Date();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        lbmb.setCreator_id(String.valueOf(user.getUserId()));
        lbmb.setCreator_name(user.getUserName());
        int count = wlLbmbService.insertWlLbmb(lbmb);
		/*// ==============================记录操作日志start===============================================
		SysLog sysLog = new SysLog();
		sysLog.setUserName(user.getUserName());
		sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
		sysLog.setOperationDate(date);
		if (count > 0) {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增物料类别模板成功");
		} else {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",新增物料类别模板失败");
		}
		sysLogServiceImpl.insertLog(sysLog);
		// ==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增物料类别模板[" + lbmb.getMbname() + "]",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getCountWlLbmbByCond", method = RequestMethod.POST)
    public JSONObject getCountWlLbmbByCond(HttpServletRequest request, WlLbmb lbmb) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = wlLbmbService.getCountWlLbmbByCond(lbmb);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/updateWlLbmb", method = RequestMethod.POST)
    public JSONObject updateWlLbmb(WlLbmb lbmb, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            //向变更表插入数据
            Map<String, Object> map = new HashMap<>();
            map.put("id", lbmb.getId());
            map.put("operationtype", "0");
            wlLbmbService.insertWlLbmbUpdateByMap(map);

            // 获取session中用户
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            WlLbmb wllbmb = wlLbmbService.getWlLbmbById(lbmb);
            wllbmb.setMbname(lbmb.getMbname());
            wllbmb.setRemark(lbmb.getRemark());
            //wllbmb.setState("0");
            wllbmb.setUpdate_uid(String.valueOf(user.getUserId()));
            wllbmb.setUpdate_name(user.getUserName());
            wllbmb.setKktzl(9999);
            wlLbmbService.updateWlLbmb(wllbmb);
            rMsg.setRspCode(0);
            //记录日志
            SysLogUtil.insertLog("编辑物料类别模板[" + lbmb.getMbname() + "]",
                    SysLogEnum.WL_LBMB.getCode(), SysLogEnum.BJ.getCode(), request);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteWlLbMbById", method = RequestMethod.POST)
    public ResultObject deleteWlLbMbById(HttpServletRequest request, WlLbmb lbmb) {
        int ret;
        try {
            WlLbmb wllbmb = wlLbmbService.getWlLbmbById(lbmb);
            wllbmb.setStatus(lbmb.getStatus());
            wllbmb.setKktzl(0);
            wlLbmbService.updateWlLbmb(wllbmb);
            ret = 1;
        } catch (Exception e) {
            e.printStackTrace();
            ret = 0;
        }
        int f = ret > 0 ? 1 : 0;
        //记录日志
        SysLogUtil.insertLog("删除物料类别模板[" + lbmb.getMbname() + "]",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.SC.getCode(), request);
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/logicDelete", method = RequestMethod.POST)
    public ResultObject logicDelete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        int ret;
        try {
            Map<String, Object> cond = new HashMap<>();
            cond.put("status", "2");
            cond.put("ids", toList(ids));
            cond.put("kktzl", 0);
            ret = wlLbmbService.updateWlLbmbByCond(cond);
        } catch (Exception e) {
            ret = 0;
        }
        int f = ret > 0 ? 1 : 0;
        //记录日志
        SysLogUtil.insertLog("编辑物料类别模板[" + ids + "]",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.SC.getCode(), request);
        ResultObject result = new ResultObject(f, "成功删除" + ret + "条数据", "删除失败");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteWllbmb", method = RequestMethod.POST)
    public ResultObject deleteWllbmb(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        int ret;
        try {
            Map<String, Object> cond = new HashMap<>();
            cond.put("ids", toList(ids));
            ret = wlLbmbService.deleteWlLbmbByCond(cond);
        } catch (Exception e) {
            ret = 0;
        }
        int f = ret > 0 ? 1 : 0;
        //记录日志
        SysLogUtil.insertLog("编辑物料类别模板[" + ids + "]",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.SC.getCode(), request);
        ResultObject result = new ResultObject(f, "成功删除" + ret + "条数据", "删除失败");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/copyWlLbmb", method = RequestMethod.POST)
    public ResultObject copyWlLbmb(HttpServletRequest request, WlLbmb lbmb) {
        int ret;
        String error = "";
        try {
            // 获取session中用户
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            Map<String, Object> condMap = new HashMap<>();
            condMap.put("p_mbname", lbmb.getMbname());
            condMap.put("p_userid", user.getUserId());
            condMap.put("p_username", user.getUserName());
            condMap.put("p_wl_lbmb_from", lbmb.getId());
            condMap.put("p_lbbm_to", lbmb.getLbbm());
            error = wlLbmbService.copyWlLbmb(condMap);
            if (error.indexOf("成功") < 0) {
                ret = 0;
            } else {
                ret = 1;
                String[] results = error.split(",");
                if (results.length == 2 && results[1].length() == 8) {//判断是否添加成功，并且返回‘成功，XXXXXXXX’的格式
                    if (lbmb.getOpe().equals("admin")) {//如果是管理员进行的复制操作，直接修改状态为审批通过
                        WlLbmb wllbmb = new WlLbmb();
                        wllbmb.setId(results[1]);
                        WlLbmb updateWlLbmb = wlLbmbService.getWlLbmbById(wllbmb);
                        updateWlLbmb.setKktzl(9999);
                        updateWlLbmb.setState("4");
                        wlLbmbService.updateWlLbmb(updateWlLbmb);
                    }
                    SysLogUtil.insertLog("根据选择的模板" + lbmb.getId() + "进行模板复制操作",
                            SysLogEnum.WL_LBMB.getCode(), SysLogEnum.FZ.getCode(), request);
					/*// 获取当前日期
					Date date = new Date();
					SysLog sysLog = new SysLog();
					sysLog.setUserName(user.getUserName());
					sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
					sysLog.setOperationDate(date);
					if (ret > 0) {
						sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
								+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",根据选择的模板"+lbmb.getId()+"进行模板复制操作成功");
					} else {
						sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
								+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",根据选择的模板"+lbmb.getId()+"进行模板复制操作失败");
					}
					sysLogServiceImpl.insertLog(sysLog);*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret = 0;
        }
        int f = ret > 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "复制模板成功", "复制模板失败：" + error);
        return result;
    }


    @SuppressWarnings({"unchecked", "unused"})
    @RequestMapping(value = "wlLbMbExport", method = RequestMethod.GET)
    @ResponseBody
    public void wlLbMbExport(HttpServletResponse response, HttpServletRequest request) {
        List<String> lbbms = StringUtil.splitAsList(request.getParameter("mblbbms"),",");
        List<String> mbids = StringUtil.splitAsList(request.getParameter("mbids"),",");
        List<String> tablenames = new ArrayList<>();
        List<XSSFWorkbook> workList = new ArrayList<>();
        for (int m = 0; m < lbbms.size(); m++) {
            tablenames.add(lbbms.get(m) + "_" + mbids.get(m));

            // 声明一个工作薄
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFCellStyle style = workbook.createCellStyle();
            DataFormat format = workbook.createDataFormat();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            font.setFontHeight(10);
            style.setFont(font);
            style.setDataFormat(format.getFormat("@"));

            XSSFCellStyle style2 = workbook.createCellStyle();
            style2.setAlignment(HorizontalAlignment.CENTER);
            style2.setVerticalAlignment(VerticalAlignment.CENTER);
            XSSFFont font2 = workbook.createFont();
            font2.setFontHeight(10);
            style2.setFont(font2);
            style2.setDataFormat(format.getFormat("@"));

            XSSFCellStyle style3 = workbook.createCellStyle();
            XSSFFont font3 = workbook.createFont();
            font3.setFontHeight(10);
            style3.setFont(font2);
            style3.setDataFormat(format.getFormat("@"));
            XSSFRow row = null;
            XSSFCell cell = null;
            Comment comment = null;

            List<WlLbmbtzlDto> tzlList = wlLbmbtzlService.getWlLbmbtzlDtoList(mbids.get(m));  //获取模板特征量
            WlLbmb wlmb = new WlLbmb();
            wlmb.setId(mbids.get(m));
            WlLbmb getWlLbmb = wlLbmbService.getWlLbmbById(wlmb);   //获取模板信息
            XSSFSheet sheet = workbook.createSheet(getWlLbmb.getMbname().replaceAll("[/*<>\\\\：？\"“']", " "));
            XSSFRow row1 = sheet.createRow(0);
            XSSFRow row2 = sheet.createRow(1);
            XSSFRow row3 = sheet.createRow(2);
            int hcol = 0;
            for (int j = 0; j < tzlList.size(); j++) {
                WlLbmbtzlDto tzlDto = tzlList.get(j);
                addCell(sheet, row1, "特征量" + (j + 1) + " " + tzlDto.getTzlmc(), hcol, style);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, hcol, hcol + 4));
                String tmpinfo = "";
                if (StringUtils.trimToEmpty(tzlDto.getNecessary()).equals("1")) {
                    tmpinfo = "必填";
                } else {
                    tmpinfo = "非必填";
                }
                if (StringUtils.trimToEmpty(tzlDto.getChooseable()).equals("1")) {
                    tmpinfo += "，必选";
                } else {
                    tmpinfo += "，非必选";
                }
                if (StringUtils.trimToEmpty(tzlDto.getJldwlms()).equals("1")) {
                    tmpinfo += "，是";
                } else {
                    tmpinfo += "，否";
                }
                addCell(sheet, row2, tmpinfo, hcol, style2);
                sheet.addMergedRegion(new CellRangeAddress(1, 1, hcol, hcol + 4));
                addCell(sheet, row3, "前置符号", hcol, style2);
                addCell(sheet, row3, "特征量值", hcol + 1, style2);
                addCell(sheet, row3, "后置符号", hcol + 2, style2);
                addCell(sheet, row3, "计量单位", hcol + 3, style2);
                addCell(sheet, row3, "连接符号", hcol + 4, style2);

                if (!ObjectUtils.isEmpty(tzlDto.getQzfhList())) {
                    List<WlLbmbTzlfh> list = tzlDto.getQzfhList();
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.getRow(3 + i);
                        if (row == null) {
                            row = sheet.createRow(3 + i);
                        }
                        addCell(sheet, row, list.get(i).getFhname(), hcol, style3);
                    }
                }
                if (!ObjectUtils.isEmpty(tzlDto.getTzlzList())) {
                    List<WlLbmbtzlqz> list = tzlDto.getTzlzList();
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.getRow(3 + i);
                        if (row == null) {
                            row = sheet.createRow(3 + i);
                        }
                        addCell(sheet, row, list.get(i).getQz(), hcol + 1, style3);
                    }
                }
                if (!ObjectUtils.isEmpty(tzlDto.getHzfhList())) {
                    List<WlLbmbTzlfh> list = tzlDto.getHzfhList();
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.getRow(3 + i);
                        if (row == null) {
                            row = sheet.createRow(3 + i);
                        }
                        addCell(sheet, row, list.get(i).getFhname(), hcol + 2, style3);
                    }
                }
                if (!ObjectUtils.isEmpty(tzlDto.getJldwList())) {
                    List<WlLbmbTzlfh> list = tzlDto.getJldwList();
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.getRow(3 + i);
                        if (row == null) {
                            row = sheet.createRow(3 + i);
                        }
                        addCell(sheet, row, list.get(i).getFhname(), hcol + 3, style3);
                    }
                }
                if (!ObjectUtils.isEmpty(tzlDto.getLjfhList())) {
                    List<WlLbmbTzlfh> list = tzlDto.getLjfhList();
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.getRow(3 + i);
                        if (row == null) {
                            row = sheet.createRow(3 + i);
                        }
                        addCell(sheet, row, list.get(i).getFhname(), hcol + 4, style3);
                    }
                }
                hcol += 5;
            }
            workList.add(workbook);
        }
        String f = "物料类别模板";
        setResponseHeader(response, f);
        OutputStream out = null;
        String delPath = "";
        try {
            out = response.getOutputStream();
            delPath = toExcel(tablenames, workList, request, f, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.delPointFile(delPath);
        }
    }

    /**
     * excel添加单元格
     *
     * @param row
     * @param str
     * @param columnIndex
     * @param style
     * @return
     */
    Cell addCell(XSSFSheet sheet, Row row, String str, int columnIndex, CellStyle style) {
        Cell cell = row.createCell(columnIndex);
        sheet.setDefaultColumnStyle(columnIndex, style);
        cell.setCellValue(str);
        if (style != null) {
            cell.setCellStyle(style);
        }
        return cell;
    }

    /**
     * 设置响应头
     */

    public void setResponseHeader(HttpServletResponse response, String filename) {

        try {
            filename = new String(filename.getBytes("GBK"), "iso8859-1");
            response.setContentType("application/msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + filename + ".zip");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public String toExcel(List<String> excelnameList,
                          List<XSSFWorkbook> workbooks, HttpServletRequest request,
                          String filename, OutputStream out) throws IOException {
        // File zip = new File(request.getRealPath("/excel") + filename +
        // ".zip");// 压缩文件,用于服务器上保存
        File zip = new File(filename + ".zip");// 压缩文件
        File srcfile[] = new File[excelnameList.size()];

        // 生成excel
        for (int i = 0; i < workbooks.size(); i++) {
            String fileName = excelnameList.get(i).replace(" ", "") + ".xlsx";
            //fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
            FileOutputStream o = null;
            //fileName=filename+"-"+fileName;
            srcfile[i] = new File(fileName);
            try {
                o = new FileOutputStream(fileName);
                workbooks.get(i).write(o);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (o != null) {
                    o.flush();
                    o.close();
                }
            }
        }

        this.ZipFiles(srcfile, zip);

        FileInputStream inStream = new FileInputStream(zip);
        byte[] buf = new byte[4096];
        int readLength;
        while (((readLength = inStream.read(buf)) != -1)) {
            out.write(buf, 0, readLength);
        }
        inStream.close();
        String path = zip.getAbsolutePath().toString();
        path = path.substring(0, path.lastIndexOf(File.separator));
        return path;
    }

    public void ZipFiles(File[] srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
            for (int i = 0; i < srcfile.length; i++) {
                FileInputStream in = new FileInputStream(srcfile[i]);
                ZipEntry zipEntry = new ZipEntry(srcfile[i].getName());
                zipEntry.setUnixMode(644);//解决linux乱码
                out.putNextEntry(zipEntry);
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }

            out.setEncoding("gbk");
            out.close();
            srcfile.clone();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定目录下的特定文件
     */
    public boolean delPointFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                if (tempList[i].lastIndexOf(".xlsx") > 0 || tempList[i].lastIndexOf(".zip") > 0) {
                    temp.delete();
                }
            }
        }
        return flag;
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbListById", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlLbmbListById(HttpServletRequest request, WlLbmb wlmb) {
        Map paramMap = RequestUtils.paramToMap(request, WlLbmb.class, false);
        PageInfo pageInfo = wlLbmbService.getWlLbmbById(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/submitWlLbmbs", method = RequestMethod.POST)
    public JSONObject submitWlLbmbs(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String ids = request.getParameter("ids");
        String msg = "";
        //校验
        List<String> idList = checkMb(ids);
        if (toList(ids).size() > idList.size()) {
            msg = "至少存在一条数据校验未通过！\n";
        }
        //提交
        //没有流程  直接审核通过
        if (idList.size() > 0) {
            Map<String, Object> condMap = new HashMap<>();
            condMap.put("state", "4");//没有配置流程直接审核通过
            condMap.put("submit_time", new Date());
            condMap.put("ids", idList);
            wlLbmbService.updateWlLbmbByCond(condMap);

            msg += "成功提交" + idList.size() + "条数据";

            //记录日志
            SysLogUtil.insertLog("提交物料类别模板[" + idList + "]",
                    SysLogEnum.WL_LBMB.getCode(), SysLogEnum.TJ.getCode(), request);
        }
        jsonObject.put("msg", msg);
        return jsonObject;
    }

    public List<String> checkMb(String ids) {
        List<String> idList = new ArrayList<String>();
        String[] id = ids.split(",");
        int count = 0;
        WlLbmbtzl wlLbmbtzl = new WlLbmbtzl();
        WlLbmb wlLbmb = new WlLbmb();
        Map<String, Object> cond = new HashMap<>();
        for (int i = 0; i < id.length; i++) {
            wlLbmbtzl.setWl_lbmb_id(id[i]);
            wlLbmbtzl.setStatus("1");
            count = wlLbmbtzlService.getWlLbmbtzlListCountByCond(wlLbmbtzl);
            wlLbmb.setId(id[i]);
            WlLbmb getWlLbmb = wlLbmbService.getWlLbmbById(wlLbmb);   //获取模板信息
            if (count == 0) {
                cond.put("state", "1");
                cond.put("id", id[i]);
                cond.put("errtext", "该模板下没有模板特征量！");
                wlLbmbService.updateWlLbmbByCond(cond);
            } else {
                if (!getWlLbmb.getState().equals("4") && !getWlLbmb.getState().equals("5")) {
                    cond.put("state", "3");
                    cond.put("id", id[i]);
                    wlLbmbService.updateWlLbmbByCond(cond);
                    idList.add(id[i]);
                }
            }
        }
        return idList;
    }

    /**
     * 导入物料模板特征量取值模板
     */
    @RequestMapping(value = "ExportwlLbmbtzlz", method = RequestMethod.GET)
    @ResponseBody
    public String ExportwlLbmbtzlz(HttpServletResponse response, HttpServletRequest request) {

        String path = IoUtil.getTemplatePath();
        String fileName = TemplateName.WL_LBMB_TZLQZ_TEMPLATE;//服务器上存的文件名
        String uploadFileName = "物料模板特征量取值创建-维护模板";//给用户下载看到的文件名
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
        //记录日志
        SysLogUtil.insertLog("导入物料模板特征量取值模板",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.PD.getCode(), request);
	    	/*InputStream inStream = null;
			String fileName = null;
			OutputStream outStream = null;
			try {
				String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
				path=path.replace('/', '\\'); // 将/换成\
				path=path.replace("classes\\", ""); //去掉class\
				path=path.replace("file:\\", ""); //file:\
				path += "doc\\dataTemplate";
				fileName = "物料模板特征量取值创建-维护模板.xlsx";
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/vnd.ms-excel");
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
				File file = new File(path,fileName);
				inStream = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len;
				outStream = response.getOutputStream();
				fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
				while((len = inStream.read(bytes)) != -1 ) {
					outStream.write(bytes, 0, len);
		        }
				outStream.flush();
				outStream.close();
				outStream = null;
				response.flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(inStream != null){
					try{inStream.close();}
					catch(Exception e){}
				}
			}*/
        return null;
    }

    /**
     * 导出模板
     */
    @RequestMapping(value = "ExportwlLbmb", method = RequestMethod.GET)
    @ResponseBody
    public String exportWlLbmb(HttpServletResponse response, HttpServletRequest request) {

        String path = IoUtil.getTemplatePath();
        String fileName = TemplateName.WL_LBMB_TEMPLATE;//服务器上存的文件名
        String uploadFileName = "物料模板创建-维护模板";//给用户下载看到的文件名
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
	    	/*InputStream inStream = null;
			String fileName = null;
			OutputStream outStream = null;
			try {
				String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
				path=path.replace('/', '\\'); // 将/换成\
				path=path.replace("classes\\", ""); //去掉class\
				path=path.replace("file:\\", ""); //file:\
				path += "doc\\dataTemplate";
				fileName = "物料模板创建-维护模板.xlsx";
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/vnd.ms-excel");
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
				File file = new File(path,fileName);
				inStream = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len;
				outStream = response.getOutputStream();
				fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
				while((len = inStream.read(bytes)) != -1 ) {
					outStream.write(bytes, 0, len);
		        }
				outStream.flush();
				outStream.close();
				outStream = null;
				response.flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(inStream != null){
					try{inStream.close();}
					catch(Exception e){}
				}
			}*/
        return null;
    }

    /**
     * 导入物料模板特征量取值
     *
     * @param response
     * @param request
     * @return
     * @author jyh
     * @date 2017-04-11
     */
    @RequestMapping(value = "importMbTzlqzData", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject importMbTzlqzData(@RequestParam("excel") CommonsMultipartFile[] files,
                                          HttpServletResponse response, HttpServletRequest request) {
        ResultObject resuObj = null;
        String bool = "true";
        String info = null;
        try {
            MultipartFile file = files[0];
            if (null == file) {
                bool = "false";
                info = "\n文件上传异常！";
            } else {
                InputStream input = file.getInputStream();
                Map<String, Object> map = wlLbmbService.importWllbmbData(input);
                if (!(Boolean) map.get("success")) {
                    bool = "false";
                }
                info = (String) map.get("info");

            }

        } catch (IOException e) {
            bool = "false";
            info = e.getMessage();
        }
        //错误文档
        if ("false".equals(bool)) {
            String fileName = "wlmbtzlqzImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
            try {
                ExportUtil.errTxt(info, fileName);
                info = fileName;//返回给前台的文件名
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
	        	/*ExcelUtil eu=new ExcelUtil();
	        	try {
					String fileName="物料模板特征量取值批量导入"+"@@@@"+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+".txt";
					eu.errTxt(info, fileName);
					info = fileName;
				} catch (IOException e) {
					e.printStackTrace();
				}*/
        }
        //记录日志
        SysLogUtil.insertLog("导入物料模板特征量取值",
                SysLogEnum.WL_LBMB.getCode(), SysLogEnum.PD.getCode(), request);
        resuObj = new ResultObject(bool, info);
        return resuObj;
    }

    /**
     * 导入物料模板
     *
     */
    @SuppressWarnings("static-access")
    @RequestMapping(value = "excelImportOld", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject excelImportOld(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String tableName = request.getParameter("tableName");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            //记录日志
            SysLogUtil.insertLog("导入物料模板",
                    SysLogEnum.WL_LBMB.getCode(), SysLogEnum.PD.getCode(), request);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = excelImport.getWorkbook(uploadFile);
            int sheetNum = 0;
            // 得到sheet总数
            sheetNum = book.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = book.getSheetAt(i);
                List<Object[]> valueList = excelImport.read(sheet);
                // 插入数据
                if (valueList != null && valueList.size() > 0) {
                    result = checkImportList(valueList, tableName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * * <p>Title: 校验用户输入的数据</p>
     * <p>Company:@param valueList
     * <p>Company:@param tableName
     * <p>Company:@param conn
     * <p>Company:@return </p>
     */
    @RequestMapping(value = "/checkImportListOld", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject checkImportListOld(List<Object[]> valueList, String tableName) {
        ExcelUtil eu = new ExcelUtil();
        String fileName = "";
        ResultObject resuObj = null;
        StringBuffer sb = new StringBuffer();//声明拼接符
        valueList.remove(0);
        if (0 != valueList.size() && null != valueList) {
            for (int j = 0; j < valueList.size(); j++) {//获取用户将导入的数据n条
                String[] row = (String[]) valueList.get(j);//获取行
                for (int k = 0; k < row.length; k++) {
                    String cell = row[k];//获取每固定行一列（0,0）
                    sb.append(checkColumnOld(j, k, cell, row));
                }

            }
        } else {
            sb.append("@@@@" + "请在模板中填写需要导入的数据！");
        }

        if (sb.toString().equals("")) {
            String[] headArray = {"USER_NAME", "USER_ACCOUNT", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
            List<String> sqls = genSqlOld(tableName, valueList, headArray);
            boolean sucess = jdbcDao.executeSqlList(sqls, true);
            if (sucess) {
                resuObj = new ResultObject("true", "导入成功!");
            }
        } else {
            try {
                fileName = "物料模板批量导入" + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                eu.errTxt(sb.toString(), fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            resuObj = new ResultObject("false", fileName);
        }
        return resuObj;
    }

    public String checkColumnOld(int row, int column, String cell, String[] coll) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        if (column == 0) {//说明是第一列（校验小类代码）
            if (cell.equals("") || cell == null || cell.equals(" ")) {//如果数据为空
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码为空！");
            } else {
                if (cell.length() == 6) {
                    WlLb wllb = new WlLb();
                    wllb.setLbbm(cell);
                    WlLb wlLb = wlLbService.getWlLbById(wllb);
                    if (null == wlLb) {
                        sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码" + "'" + cell + "'" + "不存在！");
                    }
                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码填写错误,请输入6位的小类代码！");
                }
            }

        } else if (column == 1) {//说明是第二列（校验模板名称）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,模板名称为空！");
            } else {
                WlLbmb lbmb = new WlLbmb();
                lbmb.setMbname(cell);
                int count = wlLbmbService.getWlLbmbListCountByCond(lbmb);
                if (count > 0) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,模板名称已存在!");
                }
            }
        }
        return sb.toString();

    }

    /*
     * @description:向数据库表中插入数据(1000行插入一次)
     * @param tableName,conn,sqlStr,subList,headArray
     * @return
     * @time:2016年9月07日
     */
    public List<String> genSqlOld(String tableName, List<Object[]> subList, String[] headArray) {
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);

        List<String> sqls = new ArrayList<String>();
        // 获取值集合
        for (int j = 0; j < subList.size(); j++) {
            StringBuffer sb = new StringBuffer("");
            sb.append(" insert into " + tableName + " (ID,")
                    .append("LBBM,MBNAME,REMARK,WL_LB_ID,KKTZL,STATUS,STATE,CREATOR_ID,CREATOR_NAME,CREATE_TIME,")
                    .append("VERSION,AUTO_CREATE_WL)")
                    .append(" VALUES( WL_LBMB_seq.nextval,");

            String[] row = (String[]) subList.get(j);
            WlLb wllb = new WlLb();
            wllb.setLbbm(row[0]);
            WlLb wlLb = wlLbService.getWlLbById(wllb);
            sb.append("'").append(row[0]).append("',").append("'").append(row[1]).append("',")
                    .append("'").append(row[2].trim()).append("',")
                    .append("'").append(wlLb.getLbbmId()).append("',").append("'9999', '1', '0', ")
                    .append("'").append(user.getUserId()).append("',")
                    .append("'").append(user.getUserName()).append("', sysdate, 0, '0' )");

            sqls.add(sb.toString());
            System.out.print(sb.toString());
        }
        return sqls;
    }

    //----------------------------新的导入----------------------------//

    /**
     * 导入物料模板
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "excelImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject excelImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        String str;
        try {
            ExcelUtil eu = new ExcelUtil();
            String fileName = "";
            List<String[]> valueList = readMb(response, request);
            if (valueList == null || valueList.size() == 0) {
                result = new ResultObject("false", "请在模板中填写需要导入的数据！");
                return result;
            }

            //验证数据
            Map<String, List<WlLbmbtzlImp>> map = new HashMap<String, List<WlLbmbtzlImp>>();
            str = checkMBData(valueList, map);
            if (!StringUtils.isEmpty(str)) {
                //写入错误日志
                fileName = "mbplImport" + "@@@@" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
                try {
                    ExportUtil.errTxt(str, fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
					/*try {
						fileName="物料模板批量导入"+"@@@@"+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+".txt";
						eu.errTxt(str.toString(), fileName);
					} catch (IOException e) {
						e.printStackTrace();
					}*/
                result = new ResultObject("false", fileName);
                return result;
            }

            //插入数据
            //记录日志
            SysLogUtil.insertLog("导入物料模板",
                    SysLogEnum.WL_LBMB.getCode(), SysLogEnum.PD.getCode(), request);
            insertWllbMbData(map);
            result = new ResultObject("true", "导入成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public List<String[]> readMb(HttpServletResponse response, HttpServletRequest request) {
        try {
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = excelImport.getWorkbook(uploadFile);

            Sheet sheet = book.getSheetAt(0);
            int rownum1 = sheet.getPhysicalNumberOfRows(); // Excel 中的记录行数
            if (rownum1 <= 0) {
                return null;
            }
            //用来记录excel值
            List<String[]> valueList = new ArrayList<String[]>();
            //循环遍历每一行、每一列。
            for (int i = 1; i < rownum1; i++) {
                Row row = sheet.getRow(i);
                if (null != row || !"".equals(row)) {
                    int rownum2 = 18;
                    String[] rowObject = new String[rownum2];
                    for (int j = 0; j < rownum2; j++) {
                        String value = getCellVal(sheet, j, i);
                        rowObject[j] = value;
                    }

                    //将这行添加到list。
                    valueList.add(rowObject);
                }
            }
            return valueList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 1 小类代码：state = 4，status = 1
     * 2 符号（前置，后置，连接）必须在wl_fh表中
     * 3 计量单位必须在   表中维护
     *
     * @param mb
     */
    private String checkMBData(List<String[]> mb, Map<String, List<WlLbmbtzlImp>> map) {
        Map<String, String> paramMap = new HashMap<String, String>();
        StringBuffer sb = new StringBuffer();//存放错误信息
        //开始验证
        int currentError = 0;

        WlFh wlFh = new WlFh();
        wlFh.setStatus("1");

        //符号
        wlFh.setFhtype("1");
        Map<String, String> qzfh = ObjectToString(wlFhService.getWlFhNoPageByCond(wlFh));
        //后置
        wlFh.setFhtype("2");
        Map<String, String> hzfh = ObjectToString(wlFhService.getWlFhNoPageByCond(wlFh));
        //连接
        wlFh.setFhtype("3");
        Map<String, String> ljf = ObjectToString(wlFhService.getWlFhNoPageByCond(wlFh));

        //计量单位
        Map<String, Object> jldwmap = new HashMap<String, Object>();
        jldwmap.put("status", "1");
        Map<String, String> jldws = JldwToString(wlbmJldwDao.getWlbmJldwListByCond(jldwmap));

        Map<String, WlLb> rightWlLb = new HashMap<String, WlLb>();
        Map<String, String> errorWlLb = new HashMap<String, String>();

        WlLbmbtzlImp rowObj = null;
        for (int i = 0; i < mb.size(); i++) {
            if (currentError >= 20) {
                break;
            }

            String errorRowInfo = "\r\n第" + (i + 2) + "行";
            //从第一行开始校验
            String[] obj = mb.get(i);
            //小类代码
            String lbbm = obj[0];
            //模版名称
            String mbmc = obj[2];
            //特征量序号
            String tzlxh = obj[3];
            //特征量名称
            String tzlmc = obj[4];
            //前置符号
            String qz = obj[5];
            String qzsfkk = obj[6];
            String sfbt = obj[7];
            String sfbx = obj[8];
            String sfsz = obj[9];
            String sfsyqzsxx = obj[10];
            String qzsx = obj[11];
            String qzxx = obj[12];
            //后置符号
            String hz = obj[13];
            String hzsfkk = obj[14];
            //计量单位
            String jldw = obj[15];
            //计量单位是否加入长描述
            String jldwlms = obj[16];
            //连接符
            String lj = obj[17];

            //去空
            if (StringUtils.isEmpty(lbbm) && StringUtils.isEmpty(tzlxh)) {
                continue;
            }

            float sx = 0;
            if (!StringUtils.isEmpty(qzsx)) {
                sx = Float.parseFloat(qzsx);
            }
            float xx = 0;
            if (!StringUtils.isEmpty(qzxx)) {
                xx = Float.parseFloat(qzxx);
            }

            //将每一行数据装到rowObj对象中
            rowObj = new WlLbmbtzlImp();
            rowObj.setQzsx(sx);
            rowObj.setQzxx(xx);
            rowObj.setTzlmc(tzlmc);

            //前置符号是否可空
            if ("是".equals(qzsfkk)) {
                rowObj.setQzfhsfkk("0");
            } else if ("否".equals(qzsfkk)) {
                rowObj.setQzfhsfkk("1");
            } else {
                sb.append(errorRowInfo + "【前置符号是否可空】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //是否必填
            if ("是".equals(sfbt)) {
                rowObj.setNecessary("1");
            } else if ("否".equals(sfbt)) {
                rowObj.setNecessary("0");
            } else {
                sb.append(errorRowInfo + "【特征量是否必填】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //是否必选
            if ("是".equals(sfbx)) {
                rowObj.setChooseable("1");
            } else if ("否".equals(sfbx)) {
                rowObj.setChooseable("0");
            } else {
                sb.append(errorRowInfo + "【特征量是否必选】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //是否数字
            if ("是".equals(sfsz)) {
                rowObj.setQzsfwsz("1");
            } else if ("否".equals(sfsz)) {
                rowObj.setQzsfwsz("0");
            } else {
                sb.append(errorRowInfo + "【特征量是否数字】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //后置是否可空
            if ("是".equals(hzsfkk)) {
                rowObj.setHzfhsfkk("0");
            } else if ("否".equals(hzsfkk)) {
                rowObj.setHzfhsfkk("1");
            } else {
                sb.append(errorRowInfo + "【后置符号是否可空】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //是否使用取值上下限
            if ("是".equals(sfsyqzsxx)) {
                rowObj.setXxsxbz("1");
            } else if ("否".equals(sfsyqzsxx)) {
                rowObj.setXxsxbz("0");
            } else {
                sb.append(errorRowInfo + "【是否使用取值上下限】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            //计量单位是否加入长描述
            if ("是".equals(jldwlms)) {
                rowObj.setJldwlms("1");
            } else if ("否".equals(jldwlms)) {
                rowObj.setJldwlms("0");
            } else {
                sb.append(errorRowInfo + "【记量单位是否加入长描述】值只能填【是】或【否】!");
                currentError++;
                //continue;
            }
            String param_key = lbbm + ";" + mbmc + ";" + tzlxh;
            String value = "";

            //小类代码校验开始
            //1 小类代码不能为空
            if (StringUtils.isEmpty(lbbm)) {
                sb.append(errorRowInfo + "小类代码为空!");
                currentError++;
                continue;
            }

            //2 小类代码存在且有效,优先从正确的或者错误的MAP中查询该小类对象，如果都不存在，在去数据库中查询
            WlLb wllb = null;
            String msg = "";
            if (errorWlLb.containsKey(lbbm)) {
                msg = errorWlLb.get(lbbm);
                sb.append(msg);
                currentError++;
                continue;
            }

            if (rightWlLb.containsKey(lbbm)) {
                wllb = rightWlLb.get(lbbm);
            } else {
                WlLb querywllb = new WlLb();
                querywllb.setLbbm(lbbm);
                wllb = wlLbService.getWlLbById(querywllb);
                if (wllb == null) {
                    msg = errorRowInfo + "小类代码：" + lbbm + "不存在!";
                    sb.append(msg);
                    errorWlLb.put(lbbm, msg);
                    currentError++;
                    continue;
                }
                if ("1".equals(wllb.getNouse())) {
                    msg = errorRowInfo + "小类代码：" + lbbm + "在系统中状态不能为停用!";
                    sb.append(msg);
                    errorWlLb.put(lbbm, msg);
                    currentError++;
                    continue;
                }
                rightWlLb.put(lbbm, wllb);
            }

            rowObj.setLbbm(lbbm);
            String wllbbm_id = wllb.getLbbmId();
            rowObj.setWl_lb_id(wllbbm_id);

            //模板名称
            if (StringUtils.isEmpty(mbmc)) {
                sb.append(errorRowInfo + "模板名称为空!");
                currentError++;
                continue;
            }


            if (mbmc.length() >= 150) {
                sb.append(errorRowInfo + "模板名称:" + obj[2] + "过长，不能超过150个字符!");
                currentError++;
                continue;
            }

            //特征量序号不能重
            if (StringUtils.isEmpty(tzlxh)) {
                sb.append(errorRowInfo + "模板特征量序号为空!");
                currentError++;
                //continue;
            }
            if (paramMap.containsKey(param_key)) {
                sb.append(errorRowInfo + "模板特征量序号:" + obj[3] + "重复!");
                currentError++;
                //continue;
            } else {
                paramMap.put(param_key, value);
                rowObj.setXh(Integer.parseInt(tzlxh));
            }

            //模板特征量名称
            if (StringUtils.isEmpty(tzlmc)) {
                sb.append(errorRowInfo + "特征量名称为空!");
                currentError++;
                //continue;
            }

            WlLbmb lbmb = new WlLbmb();
            lbmb.setMbname(mbmc);
            int count = wlLbmbService.getWlLbmbListCountByCond(lbmb);
            if (count > 0) {
                sb.append(errorRowInfo + "模板名称在系统中已存在!");
                continue;
            }

            //验证前置符号
            if (!StringUtils.isEmpty(qz)) {
                boolean fhFlag = true;
                String q[] = qz.split(";");
                for (String str : q) {
                    if (!qzfh.containsKey(str)) {
                        sb.append(errorRowInfo + "前置符号:" + str + "在系统中不存在!");
                        currentError++;
                        fhFlag = false;
                        break;
                    }
                    //将前置符唯一码存在对象中
                    String qzWym = rowObj.getQz_wym();
                    if (StringUtils.isEmpty(qzWym)) {
                        rowObj.setQz_wym(qzfh.get(str));
                    } else {
                        rowObj.setQz_wym(qzWym + ";" + qzfh.get(str));
                    }
                }
                if (!fhFlag) {
                    continue;
                }
            }

            //验证后置符号
            if (!StringUtils.isEmpty(hz)) {
                boolean fhFlag = true;
                String q[] = hz.split(";");
                for (String str : q) {
                    if (!hzfh.containsKey(str)) {
                        sb.append(errorRowInfo + "后置符号:" + str + "不存在!");
                        currentError++;
                        fhFlag = false;
                        break;
                    }
                    //将后置符唯一码存在对象中
                    String hzWym = rowObj.getHz_wym();
                    if (StringUtils.isEmpty(hzWym)) {
                        rowObj.setHz_wym(hzfh.get(str));
                    } else {
                        rowObj.setHz_wym(hzWym + ";" + hzfh.get(str));
                    }
                }
                if (!fhFlag) {
                    continue;
                }
            }

            //验证连接符
            if (!StringUtils.isEmpty(lj)) {
                boolean fhFlag = true;
                String q[] = lj.split(";");
                for (String str : q) {
                    if (!ljf.containsKey(str)) {
                        sb.append(errorRowInfo + "连接符号:" + str + "不存在!");
                        currentError++;
                        fhFlag = false;
                        break;
                    }
                    //将连接符号唯一码存在对象中
                    String ljfWym = rowObj.getLj_wym();
                    if (StringUtils.isEmpty(ljfWym)) {
                        rowObj.setLj_wym(ljf.get(str));
                    } else {
                        rowObj.setLj_wym(ljfWym + ";" + ljf.get(str));
                    }
                }
                if (!fhFlag) {
                    continue;
                }
            }

            //计量单位
            if (!StringUtils.isEmpty(jldw)) {
                boolean fhFlag = true;
                String jl[] = jldw.split(";");
                for (String str : jl) {
                    if (!jldws.containsKey(str)) {
                        sb.append(errorRowInfo + "计量单位:" + str + "不存在!");
                        currentError++;
                        fhFlag = false;
                        break;
                    }
                    //将计量单位符号，唯一码装到对象中
                    String jldwWym = rowObj.getJldw_wym();
                    if (StringUtils.isEmpty(jldwWym)) {
                        rowObj.setJldw_wym(jldws.get(str));
                    } else {
                        rowObj.setJldw_wym(jldwWym + ";" + jldws.get(str));
                    }
                }
                if (!fhFlag) {
                    continue;
                }
            }


            //map
            String key = lbbm + ";" + mbmc + ";" + wllbbm_id;
            //value
            List<WlLbmbtzlImp> list = null;

            if (map.containsKey(key)) {
                list = map.get(key);
            } else {
                list = new ArrayList<WlLbmbtzlImp>();
                map.put(key, list);
            }
            list.add(rowObj);
        }

        return sb.toString();
    }

    private void insertWllbMbData(Map<String, List<WlLbmbtzlImp>> map) {
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        WlLbmbTzlfh wlLbmbTzlfh = new WlLbmbTzlfh();
        WlLbmb wlLbmb = new WlLbmb();
        for (Entry<String, List<WlLbmbtzlImp>> entry : map.entrySet()) {
            String key = entry.getKey();
            wlLbmb.setLbbm(key.split(";")[0]);
            wlLbmb.setMbname(key.split(";")[1]);
            wlLbmb.setWl_lb_id(key.split(";")[2]);
            wlLbmb.setCreator_id(String.valueOf(user.getUserId()));
            wlLbmb.setCreator_name(user.getUserName());
            wlLbmb.setKktzl(9999);
            wlLbmb.setAuto_create_wl("0");
            // 将模板数据插入到tzlmb中
            wlLbmbService.insertWlLbmb(wlLbmb);
            List<WlLbmbtzlImp> list = entry.getValue();
            for (WlLbmbtzlImp wllbmbtzl : list) {
                wllbmbtzl.setCreator_id(String.valueOf(user.getUserId()));
                wllbmbtzl.setCreator_name(user.getUserName());
                wllbmbtzl.setWl_lbmb_id(wlLbmb.getId());
                //--特殊处理，字段jldw_wym在wllbmbtzl表没有作用，但如果超长回报异常，设置为空
                String jldw = wllbmbtzl.getJldw_wym();
                if (!StringUtils.isEmpty(jldw)) {
                    wllbmbtzl.setJldw_wym(null);
                }
                wlLbmbtzlService.insertWlLbmbtzl(wllbmbtzl);
                Integer str = Integer.valueOf(wllbmbtzl.getId());
//                String str = wllbmbtzl.getId();
                String qz = wllbmbtzl.getQz_wym();
                String hz = wllbmbtzl.getHz_wym();
                String lj = wllbmbtzl.getLj_wym();

                if (!StringUtils.isEmpty(qz)) {
                    for (String s : qz.split(";")) {
                        insertTzlFh(wlLbmbTzlfh, str, Integer.valueOf(s), "1");
                    }
                }

                if (!StringUtils.isEmpty(hz)) {
                    for (String s : hz.split(";")) {
                        insertTzlFh(wlLbmbTzlfh, str, Integer.valueOf(s), "2");
                    }
                }
                if (!StringUtils.isEmpty(lj)) {
                    for (String s : lj.split(";")) {
                        insertTzlFh(wlLbmbTzlfh, str, Integer.valueOf(s), "3");
                    }
                }
                if (!StringUtils.isEmpty(jldw)) {
                    for (String s : jldw.split(";")) {
                        insertTzlFh(wlLbmbTzlfh, str, Integer.valueOf(s), "4");
                    }
                }

            }
        }
    }

    private void insertTzlFh(WlLbmbTzlfh wlLbmbTzlfh, Integer wlLbmbtzlId, Integer fhWym, String fhType) {
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        wlLbmbTzlfh.setWl_lbmbtzl_id(wlLbmbtzlId);
        wlLbmbTzlfh.setFh_wym(fhWym);
        wlLbmbTzlfh.setFh_type(fhType);
        wlLbmbTzlfh.setCreator_id(user.getUserCreateId().intValue());
//        wlLbmbTzlfh.setCreator_id(Integer.valueOf(user.getUserId()));
//        wlLbmb.setCreator_id(String.valueOf(user.getUserId()));

        wlLbmbTzlfh.setCreator_name(user.getUserName());
        wlLbmbtzlService.insertWlLbmbTzlfh(wlLbmbTzlfh);
        //日志记录
        HttpServletRequest request = null;
        SysLogUtil.insertLog("新增物料类别模板特征量符号[" + wlLbmbTzlfh.getFhname() + "]",
                SysLogEnum.WL_LBMB_TZLFH.getCode(), SysLogEnum.XZ.getCode(), request);
    }

    private Map<String, String> ObjectToString(List<WlFh> wlFhNoPageByCond) {
        Map<String, String> map = new HashMap<String, String>();
        for (WlFh wlfh : wlFhNoPageByCond) {
            map.put(wlfh.getFhname(), String.valueOf(wlfh.getWym()));
        }
        return map;
    }

    private Map<String, String> JldwToString(List<WlbmJldw> wlbmJldwListByCond) {
        Map<String, String> map = new HashMap<String, String>();
        for (WlbmJldw wlbmJldw : wlbmJldwListByCond) {
            map.put(wlbmJldw.getFh(), String.valueOf(wlbmJldw.getJldwId()));
        }
        return map;
    }

    /**
     * * <p>Title: 校验用户输入的数据</p>
     * <p>Company:@param valueList
     * <p>Company:@param tableName
     * <p>Company:@param conn
     * <p>Company:@return </p>
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "/checkImportList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject checkImportList(List<Object[]> valueList, String tableName) {
        ExcelUtil eu = new ExcelUtil();
        String fileName = "";
        ResultObject resuObj = null;
        StringBuffer sb = new StringBuffer();//声明拼接符
        valueList.remove(0);
        if (0 != valueList.size() && null != valueList) {
            for (int j = 0; j < valueList.size(); j++) {//获取用户将导入的数据n条
                String[] row = (String[]) valueList.get(j);//获取行
                for (int k = 0; k < row.length; k++) {
                    String cell = row[k];//获取每固定行一列（0,0）
                    sb.append(checkColumn(j, k, cell, row));
                }

            }
        } else {
            sb.append("@@@@" + "请在模板中填写需要导入的数据！");
        }

        if (sb.toString().equals("")) {
            String[] headArray = {"USER_NAME", "USER_ACCOUNT", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
            List<String> sqls = genSqlOld(tableName, valueList, headArray);
            boolean sucess = jdbcDao.executeSqlList(sqls, true);
            if (sucess) {
                resuObj = new ResultObject("true", "导入成功!");
            }
        } else {
            fileName = "wllbmbImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
            try {
                ExportUtil.errTxt(sb.toString(), fileName);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
				/*try {
					fileName="物料模板批量导入"+"@@@@"+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+".txt";
					eu.errTxt(sb.toString(), fileName);
				} catch (IOException e) {
					e.printStackTrace();
				}*/
            resuObj = new ResultObject("false", fileName);
        }
        return resuObj;
    }

    public String checkColumn(int row, int column, String cell, String[] coll) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        if (column == 0) {//说明是第一列（校验小类代码）
            if (cell.equals("") || cell == null || cell.equals(" ")) {//如果数据为空
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码为空！");
            } else {
                if (cell.length() == 6) {
                    WlLb wllb = new WlLb();
                    wllb.setLbbm(cell);
                    WlLb wlLb = wlLbService.getWlLbById(wllb);
                    if (null == wlLb) {
                        sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码" + "'" + cell + "'" + "不存在！");
                    }
                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,小类代码填写错误,请输入6位的小类代码！");
                }
            }

        } else if (column == 1) {//说明是第二列（校验模板名称）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,模板名称为空！");
            } else {
                WlLbmb lbmb = new WlLbmb();
                lbmb.setMbname(cell);
                int count = wlLbmbService.getWlLbmbListCountByCond(lbmb);
                if (count > 0) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,模板名称已存在!");
                }
            }
        }
        return sb.toString();

    }

    /*
     * 2017-06-29
     * jyh
     * 错误日志下载抽取至LogErrorsController中
     */

    /**
     * * <p>Title: 导入数据，错误文档</p>
     * <p>Company:@param response
     * <p>Company:@param request </p>
     */
	    /*@RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
	    @ResponseBody
	    public void downLoadErr(HttpServletResponse response,HttpServletRequest request){
	    	String fileName = request.getParameter("err_fileName");
			String path = WlLbmbController.class.getProtectionDomain().getCodeSource()
	                .getLocation().getPath();
			String file=path.substring(1, path.indexOf("/WEB-INF/classes"))+"/error_text/"+fileName;
			System.out.println("file:"+file);
			try {
				InputStream inStream = new FileInputStream(file);
				if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
				     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
				}else{
				     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
				}
				response.reset();
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/octet-stream; charset=UTF-8");
				response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
				// 循环取出流中的数据
				byte[] b = new byte[100];
				int len;
				OutputStream output=response.getOutputStream();
				while ((len = inStream.read(b)) > 0)
					output.write(b, 0, len);

				output.flush();
				output.close();
				inStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/
    public static String getCellVal(Sheet sheet, int c, int r) {
        String result = "";
        try {
            Cell cell = sheet.getRow(r).getCell(c);
            if (null != cell) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                result = cell.getStringCellValue().trim();
            }
        } catch (Exception e) {
            // 有异常就返回空字符串
        }
        return result;
    }

    /**
     * 传入一个ID字符串(以,号连接的),解析后,返回ID集合
     *
     * @param array
     * @return List<String>
     * @author jyh
     * @date 2016-09-27
     */
    public List<String> toList(String array) {
        ArrayList<String> list = new ArrayList<String>();
        if (array != null) {
            for (String string : array.split(",")) {
                list.add(string);
            }
        }
        return list;
    }

    /**
     * 冻结解冻物料类别模板
     *
     * @param request
     * @return
     * @author jyh
     * @date 2017-07-03
     */
    @ResponseBody
    @RequestMapping(value = "/updWllbmbStatus", method = RequestMethod.POST)
    public JSONObject updWllbmbStatus(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String ids = request.getParameter("ids");
        int ret = 0;//受影响行数
        try {
            Map<String, Object> cond = new HashMap<>();
            cond.put("djhd", "0");//随便填，值在sql中处理
            cond.put("ids", toList(ids));
            //cond.put("kktzl", 0);
            ret = wlLbmbService.updateWlLbmbByCond(cond);
            jsonObject.put("success", true);
            //记录日志
            SysLogUtil.insertLog("编辑物料类别模板[" + ids + "]",
                    SysLogEnum.WL_LBMB.getCode(), SysLogEnum.BJ.getCode(), request);
        } catch (Exception e) {
            jsonObject.put("success", false);
        }
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getCountdelWllbByMbBm", method = RequestMethod.POST)
    public JSONObject getCountdelWllbByMbBm(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        String lbbm = request.getParameter("lbbm");
        try {
            Map<String, Object> cond = new HashMap<>();
            cond.put("lbbm", lbbm);
            int count = wlLbmbService.getCountdelWllbByMbBm(cond);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 导出当前页数据
     *
     * @param request
     * @author liyang
     * @date 2018-01-31
     */
    @RequestMapping(value = "wlLbMbExportExcel", method = RequestMethod.POST)
    @ResponseBody
    public String wlLbMbExportExcel(HttpServletResponse response, HttpServletRequest request) {
        if (wlLbMbListByExport.size() > 0 && wlLbMbListByExport != null) {
            wlLbmbService.exportWlLbMb(wlLbMbListByExport, response);
        }
        return null;
    }

    /**
     * 导出所有数据
     */
    @RequestMapping(value = "wlLbMbExportExcel2", method = RequestMethod.POST)
    @ResponseBody
    public String wlLbMbExportExcel2(HttpServletResponse response, HttpServletRequest request) {
        String start = request.getParameter("Second_PageHelper");
        String end = request.getParameter("First_PageHelper");
        if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
            wlmbmap.put("pageNum", start);
            wlmbmap.put("limit", end);
            PageInfo pageInfo = wlLbmbService.getWlLbmbListByCond2(wlmbmap);
            List l = pageInfo.getList();
            if (l.size() > 0 && l != null) {
                wlLbmbService.exportWlLbMb(l, response);
            }
        }
        return null;
    }
}
